<?php

require_once ('config.php');

class DatabaseHelper {

    private static $m_pInstance;

    public static function getInstance() {
        if (!self::$m_pInstance) {
            self::$m_pInstance = new DatabaseHelper();
        }

        return self::$m_pInstance;
    }

    private function __construct() {
        
    }

    public function connect() {

        $conn = mysql_connect(DB_HOST, DB_USER, DB_PASS);
        if (!$conn) {
            die('Could not connect: ' . mysql_error()) . '<br/>';
        } else {
            //echo 'Connect success full to DB';
        }
        $db = mysql_select_db(DB_NAME, $conn);
        if (!$db) {
            die('Cannot connect to database: ' . mysql_error() . '<br>');
        } else {
            //echo 'Connected to database';
        }
    }

    public function query($query) {
        $result = mysql_query($query);
        if (!$result) {
            die('Invalid query: ' . mysql_error());
        }
        
        return $result;
    }

    public function select($table, $data = '', $addOn = '') {
        $data = ($data == '') ? '*' : $data;
        return mysql_query("select $data from $table $addOn");
    }

    public function insert($table, $data) {
        echo "insert into " . $table . " values($data)";
        return mysql_query("insert into " . $table . " values($data)") or die('Could insert error: ' . mysql_error());
        ;
    }

    public function update($table, $what, $where) {
        return mysql_query("update $table set $what where $where");
    }

    public function delete($table, $id = '') {
        $id = ($id == '') ? '' : "where $id";
        return mysql_query("delete from $table $id");
    }

    public function fobject($result) {
        return mysql_fetch_object($result);
    }

    public function assoc($result) {
        return mysql_fetch_assoc($result);
    }

    public function farray($result) {
        return mysql_fetch_array($result, MYSQL_NUM);
    }

    public function numberResultRow($result) {
        return mysql_num_rows($result);
    }

    public function getIncrement($table) {
        $query = mysql_fetch_assoc(mysql_query('show table status from ' . DB_NAME . " where name = '$table'"));
        return $query['Auto_increment'];
    }

    public function close() {
        mysql_close();
    }

}

?>
